package com.sangeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.baomidou.mybatisplus.core.injector.methods.SelectOne;
import com.baomidou.mybatisplus.core.injector.methods.UpdateById;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangeng.domain.ResponseResult;
import com.sangeng.domain.constants.SystemConstants;
import com.sangeng.domain.dto.AddUserDto;
import com.sangeng.domain.dto.UserDto;
import com.sangeng.domain.entity.Role;
import com.sangeng.domain.entity.RoleMenu;
import com.sangeng.domain.entity.User;
import com.sangeng.domain.entity.UserRole;
import com.sangeng.domain.vo.PageVo;
import com.sangeng.domain.vo.UpdateUserVo;
import com.sangeng.domain.vo.UserInfoVo;
import com.sangeng.enums.AppHttpCodeEnum;
import com.sangeng.handler.exception.SystemException;
import com.sangeng.mapper.UserMapper;
import com.sangeng.mapper.UserRoleMapper;
import com.sangeng.service.RoleService;
import com.sangeng.service.UserRoleService;
import com.sangeng.service.UserService;
import com.sangeng.utils.BeanCopyUtils;
import com.sangeng.utils.SecurityUtils;
import org.aspectj.weaver.ast.Literal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2024-08-16 21:16:01
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    @Override
    public ResponseResult getUserInfo() {
        Long userId = SecurityUtils.getUserId();
        User user = baseMapper.selectById(userId);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        return ResponseResult.okResult(userInfoVo);
    }

    @Override
    public ResponseResult putUserInfo(User user) {
        updateById(user);
        return ResponseResult.okResult();
    }
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public ResponseResult register(UserDto userDto) {
        //对传入的数据进行非空判断
        if (!StringUtils.hasText(userDto.getUserName())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        if (!StringUtils.hasText(userDto.getPassword())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        if (!StringUtils.hasText(userDto.getNickName())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_NICKNAME);
        }
        if (!StringUtils.hasText(userDto.getEmail())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_EMAIl);
        }
        //对传入数据查重
        if (userNameExist(userDto.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if (userNickNameExist(userDto.getNickName())){
            throw new SystemException(AppHttpCodeEnum.USERNICKNAME_EXIST);
        }
        if (email(userDto.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        //保存数据
        //对密码进行加密
        User user = BeanCopyUtils.copyBean(userDto, User.class);
        user.setPassword(passwordEncoder.encode(userDto.getPassword()));
        save(user);
        return ResponseResult.okResult();
    }

    private boolean email(String email) {
        LambdaQueryWrapper<User> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail,email);

        return count(queryWrapper)>0;
    }

    private boolean userNickNameExist(String nickName) {
        LambdaQueryWrapper<User> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickName,nickName);

        return count(queryWrapper)>0;
    }

    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);

        return count(queryWrapper)>0;
    }

    @Override
    public ResponseResult getUserList(Long pageNum, Long pageSize, String userName, String phonenumber, String status) {
       LambdaQueryWrapper<User> userLQW=new LambdaQueryWrapper<>();
       userLQW.like(StringUtils.hasText(userName),User::getUserName,userName)
               .like(StringUtils.hasText(phonenumber),User::getPhonenumber,phonenumber);
        Page<User> userPage=new Page<>(pageNum,pageSize);
        page(userPage,userLQW);
        List<UserInfoVo> userInfoVos = BeanCopyUtils.copyBeanList(userPage.getRecords(), UserInfoVo.class);
        PageVo pageVo=new PageVo(userInfoVos,userPage.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult addUser(AddUserDto addUserDto) {
        //对传入的数据进行非空判断
        if (!StringUtils.hasText(addUserDto.getUserName())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        if (!StringUtils.hasText(addUserDto.getPassword())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        if (!StringUtils.hasText(addUserDto.getNickName())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_NICKNAME);
        }
        if (!StringUtils.hasText(addUserDto.getEmail())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_EMAIl);
        }
        if (!StringUtils.hasText(addUserDto.getPhonenumber())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_EMAIl);
        }
        //对传入数据查重
        if (userNameExist(addUserDto.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if (userNickNameExist(addUserDto.getNickName())){
            throw new SystemException(AppHttpCodeEnum.USERNICKNAME_EXIST);
        }
        if (email(addUserDto.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        if (Phonenumber(addUserDto.getPhonenumber())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        //对用户密码进行加密
        User user = BeanCopyUtils.copyBean(addUserDto, User.class);
        user.setPassword(passwordEncoder.encode(addUserDto.getPassword()));
        save(user);
        return ResponseResult.okResult();
    }

    private boolean Phonenumber(String phonenumber) {
        LambdaQueryWrapper<User> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhonenumber,phonenumber);

        return count(queryWrapper)>0;
    }


    @Override
    @Transactional
    public ResponseResult deleteUser(Long id) {
        //删除用户所关联的角色信息
        LambdaQueryWrapper<UserRole> userRoleLQW=new LambdaQueryWrapper<>();
        userRoleLQW.eq(UserRole::getUserId,id);
        userRoleService.remove(userRoleLQW);
        //删除用户
        removeById(id);
        return null;
    }


    @Override
    public ResponseResult getUserById(Long userId) {
        //获取用户关联的角色id
        LambdaQueryWrapper<UserRole> userRoleLQW=new LambdaQueryWrapper<>();
        userRoleLQW.eq(UserRole::getUserId,userId);
        List<UserRole> list = userRoleService.list(userRoleLQW);
        List<Long> roleIds = list.stream().distinct().map(UserRole::getRoleId).collect(Collectors.toList());
        //查询出所有的角色 状态是启用的 0启用 1 禁用
        LambdaQueryWrapper<Role> roleLQW=new LambdaQueryWrapper<>();
        roleLQW.eq(Role::getStatus, SystemConstants.NORMAL);
        List<Role> roles = roleService.list(roleLQW);
        //获取用户信息
        User user = getById(userId);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        //封装返回的数据
        UpdateUserVo updateUserVo=new UpdateUserVo(roleIds,roles,userInfoVo);
        return ResponseResult.okResult(updateUserVo);
    }

    @Override
    @Transactional
    public ResponseResult updateUser(UserDto userDto) {
        //删除用户与角色的关联信息
        LambdaQueryWrapper<UserRole> userRoleLQW=new LambdaQueryWrapper<>();
        userRoleLQW.eq(UserRole::getUserId,userDto.getId());
        userRoleService.remove(userRoleLQW);
        //重新添加用户与角色的关系
        List<UserRole> userRoles = userDto.getRoleIds()
                .stream()
                .distinct()
                .map(m -> new UserRole(userDto.getId(), m))
                .collect(Collectors.toList());
        userRoleService.saveBatch(userRoles);
        //保存用户信息
        User user = BeanCopyUtils.copyBean(userDto, User.class);
        updateById(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult changeUserStatus(User user) {
        if ( user.getId() == 1L){
            throw  new SystemException(500,"权限不足");
        }
        updateById(user);
        return ResponseResult.okResult();
    }
}
